package cn.cms.mongo;

import cn.cms.dao.PageDao;
import org.jfaster.mango.binding.BoundSql;
import org.jfaster.mango.interceptor.Parameter;
import org.jfaster.mango.interceptor.QueryInterceptor;
import org.jfaster.mango.mapper.SingleColumnRowMapper;
import org.jfaster.mango.plugin.page.PageException;

import javax.sql.DataSource;
import java.util.Iterator;
import java.util.List;

/**
 * Created by justin on 2017/12/13.
 */
public class MysqlPageInterceptor extends QueryInterceptor {

    public void interceptQuery(BoundSql boundSql, List<Parameter> parameters, DataSource dataSource) {
        if (parameters != null & parameters.size() > 0) {
            Iterator var4 = parameters.iterator();

            while (var4.hasNext()) {
                Parameter parameter = (Parameter) var4.next();
                Object val = parameter.getValue();
                if (val instanceof PageDao) {
                    PageDao pageDao = (PageDao) val;
                    if (pageDao.getPageSize() <= 0) {
                        throw new PageException("pageSize need > 0, but pageSize is " + pageDao.getPageSize());
                    }
//                    this.handleCondition(pageDao, boundSql);
                    BoundSql totalBoundSql = boundSql.copy();
                    this.handleTotal(totalBoundSql);
                    SingleColumnRowMapper<Integer> mapper = new SingleColumnRowMapper(Integer.TYPE);
                    int total = ((Integer) this.getJdbcOperations().queryForObject(dataSource, totalBoundSql, mapper)).intValue();
                    pageDao.setTotalCount(total);


                    this.handlePage(pageDao, boundSql);
                }
            }
        }
    }

    void handleTotal(BoundSql boundSql) {
        String sql = boundSql.getSql();
        sql = "SELECT COUNT(1) FROM (" + sql + ") aliasForPage";
        boundSql.setSql(sql);
    }

/*    void handleCondition(PageDao pageDao, BoundSql boundSql) {
        String sql = boundSql.getSql();
        String condition = "";
        String finalSql = sql;
        JSONObject json = pageDao.getQueryCondition();
        if (json != null && json.size() > 0) {
            condition = getCondition(json,sql);
        }
        if (!"".equals(condition)) {
            if(sql.contains(" order ")){
               int index = sql.indexOf(" order ");
               finalSql =sql.substring(0,index) + " " + condition + sql.substring(index);
            }else {
                finalSql=sql + condition;
            }
        }
        boundSql.setSql(finalSql);
    }*/

    void handlePage(PageDao pageDao, BoundSql boundSql) {
        int startRow = pageDao.getPageNo() * pageDao.getPageSize();
        String sql = boundSql.getSql();
        if (pageDao.getOrderBy() != null && pageDao.getOrder() != null) {
            sql = sql + " order by " + pageDao.getOrderBy() + " " + pageDao.getOrder() + " limit ?, ?";
        } else {
            sql = sql + " limit ?, ?";
        }
        boundSql.setSql(sql);
        boundSql.addArg(startRow);
        boundSql.addArg(pageDao.getPageSize());
    }


    //仅用来判断正负整数，不识别小数
/*    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }*/


/*    public static String getCondition(JSONObject json,String sql) {
        Iterator it = json.keySet().iterator();
        //TODO 不支持时间类型,只支持数字和字符串
        StringBuffer sb = new StringBuffer();
        ArrayList<String> entityFields = SqlUtil.getEntityFields(SqlUtil.getSelectSqlEntity(sql));
        while (it.hasNext()) {
            String key = (String) it.next();
            String value = json.getString(key);
            if ("".equals(value) || value.contains("/")) {
                continue;
            }
            if (!isNumeric(value)) {
                if (value.startsWith("--")) {
                    value = " like " + "'%" + value.substring(2) + "%'";
                } else {
                    value = value.startsWith("++") ? "=" + "'" + value.substring(2) + "'" : " like " + "'%" + value + "%'";
                }
            } else {
                value = "=" + "'" + value + "'";
            }
            String[] keys = key.split("__");
            int count = 0 ;
            for (int i = 0; i < keys.length; i++) {
                if(entityFields.contains(keys[i])){
                    String op = count == 0 ? " AND (" : " OR ";
                    sb.append(op + SqlUtil.getSqlColumn(keys[i]) + value);
                    count++;
                }
            }
            if (count>0){
                sb.append(") ");
            }
        }
        return sb.length() > 0 ? " where " + sb.substring(5) : "";
    }*/

}